package com.hongwang.utils;

import com.hongwang.core.SpringContextHolder;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author 1
 */
public class RedisTemplateUtils {


    private static RedisTemplate<String, Object> redisTemplate = SpringContextHolder.getBean("redisTemplate");

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @param expire
     */
        public static void set(final String key, final Object value, final Integer expire,TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, expire,timeUnit);
    }

    /***
     * 计数器
     * @param key
     */
    public  static long counter(final String key){

        return  redisTemplate.opsForValue().increment(key, 1);

    }

    /***
     * 设置key的到期时间
     * @param key
     * @param expire
     * @param timeUnit
     */
    public static boolean expire(final String key,Integer expire,TimeUnit timeUnit){
       return redisTemplate.expire(key,expire,timeUnit);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T get(final String key, Class<T> clazz) {
        return (T) redisTemplate.boundValueOps(key).get();
    }

    /**
     * 读取缓存
     * @param key
     * @return
     */
    public static Object getObj(final String key){
        return redisTemplate.boundValueOps(key).get();
    }

    /**
     * 删除，根据key精确匹配
     *
     * @param key
     */
    public static void del(final String... key) {
        redisTemplate.delete(Arrays.asList(key));
    }

    /**
     * 批量删除，根据key模糊匹配
     *
     * @param pattern
     */
    public static void delpn(final String... pattern) {
        for (String kp : pattern) {
            redisTemplate.delete(redisTemplate.keys(kp + "*"));
        }
    }

    /**
     * key是否存在
     *
     * @param key
     */
    public static boolean check(final String key) {
        return redisTemplate.hasKey(key);
    }

}
